package com.seqb.common.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seqb.common.utils.RedisUtils;
import com.seqb.utils.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lilinshen
 * @title 数据量访问定时任务
 * @description 请填写相关描述
 * @date 2020/11/10
 */
public class DataAccessJob implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataAccessJob.class);

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            Object taskParams = redisUtils.get("taskParams");
            List<String> requestUrlLists = new ArrayList<>();
            if (null != taskParams) {
                JSONArray parseArray = JSON.parseArray(taskParams.toString());
                for (int i = 0; i < parseArray.size(); i++) {
                    JSONObject item = parseArray.getJSONObject(i);
                    String type = item.getString("type");
                    if ("DataAccessJob".equals(type)) {
                        JSONArray value = item.getJSONArray("value");
                        for (int j = 0; j < value.size(); j++) {
                            JSONObject jsonObject = value.getJSONObject(j);
                            requestUrlLists.add(jsonObject.getString("value"));
                        }
                    }
                }
            }
            LOGGER.info("数据量访问任务开始-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            taskList(requestUrlLists);
            LOGGER.info("数据量访问任务结束-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void taskList(List<String> requestUrlLists) {
        RestTemplate restTemplate = new RestTemplate();
        if (null != requestUrlLists && requestUrlLists.size() > 0) {
            for (int i = 0; i < requestUrlLists.size(); i++) {
                String requestUrl = requestUrlLists.get(i);
                restTemplate.getForEntity(requestUrl, Resource.class);
            }
        }
    }
}
